from django import forms
from apps.forms import FormMixin
from django.core.cache import cache

from django.contrib.auth import get_user_model
User = get_user_model()


class LoginForm(forms.Form, FormMixin):
    telephone = forms.CharField(max_length=11)
    password = forms.CharField(max_length=50, min_length=1)
    remember = forms.IntegerField(required=False)


class RegisterForm(forms.Form, FormMixin):
    telephone = forms.CharField(max_length=11)
    username = forms.CharField(max_length=50)
    password1 = forms.CharField(max_length=50, min_length=1, error_messages={
        "max_length": "密码最多不能超过50个字符",
        "min_length": "密码最少不能少于1个字符"
    })
    password2 = forms.CharField(max_length=50, min_length=1, error_messages={
        "max_length": "密码最多不能超过50个字符",
        "min_length": "密码最少不能少于1个字符"
    })
    img_captcha = forms.CharField(min_length=4, max_length=4)
    sms_captcha = forms.CharField(min_length=4, max_length=4)

    def clean(self):
        cleaned_data = super(RegisterForm, self).clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        if password1 != password2:
            raise forms.ValidationError('两次密码不一致')

        img_captcha = cleaned_data.get('img_captcha')
        cached_img_captcha = cache.get(img_captcha.lower())
        if not cached_img_captcha or cached_img_captcha != img_captcha.lower():
            raise forms.ValidationError('图形验证失败')

        sms_captcha = cleaned_data.get('sms_captcha')
        telephone = cleaned_data.get('telephone')
        cached_img_captcha = cache.get(telephone)
        if not cached_img_captcha or cached_img_captcha.lower() != sms_captcha:
            raise forms.ValidationError('手机验证失败')
        exists = User.objects.filter(telephone=telephone).exists()
        if exists:
            raise forms.ValidationError('手机号码已存在')
